# -*- coding:utf-8 -*-
from ajson import aj
from flask import request, Response

from db_base import ClassificationOrm, ArticleOrm, StarOrm, CommentOrm, UserOrm
from db_base.db_impl import MyFactory
from utils import Error
from . import article_v
from .util import article_star_comment, EchartsLine, EchartsBar, ge_echarts


@article_v.route('/list/<article_type>/')
def article_list(article_type):
    """
    获取帖子的数据
    :param article_type:
    :return:
    """
    data = request.args
    page = int(data['page'])
    limit = int(data['limit'])

    if article_type == 'all':
        cf = ClassificationOrm.orm.find('id').end()
    else:
        cf = ClassificationOrm.orm.find('id').where(name=article_type).end()
    if not cf and len(cf) <= 0:
        return Error(f'没有找到{article_type}类别', 400)

    cf_ids = [i.id for i in cf]

    from tables.article.models import Article
    count_obj = Article()

    all_data = ArticleOrm.orm \
        .find() \
        .where(classification_id__in=cf_ids) \
        .order_by('create_time') \
        .desc()

    count_sql = count_obj.orm.find('COUNT(*)', h_func=True, asses=['_count'], poly=['FROM'])
    count_sql.args[1] = "COUNT(*) AS _count"
    count_sql = count_sql << all_data
    # 数量
    count = count_sql.append('AS a')
    count = count.first().end()

    limit_data = all_data.limit((page - 1) * limit, limit).end()
    if len(limit_data) == 0:
        return Error('只有这么多了', 400)

    article_list = article_star_comment(limit_data)

    payload = {
        'code': 200,
        'message': 'ok',
        'data': article_list,
        'listQuery': {
            'page': page,
            'limit': limit
        },
        'total': count._count
    }

    return Response(aj.parse(payload), status=200)


@article_v.route('/item/<article_id>/')
def article_item(article_id):
    item = ArticleOrm.orm \
        .find() \
        .where(id=article_id) \
        .first() \
        .end()

    return Response(item.to_json(), status=200)


@article_v.route('/create/', methods=['POST'])
def article_save():
    data = aj.load(request.get_data(as_text=True))
    if 'user_id' not in data.keys() or data['user_id'] is None:
        return Error('请先登录', 400)
    line, last_id = MyFactory.createInstance('article.Article', **data).save()
    last = ArticleOrm.orm.find().where(id=last_id).first().end()

    return Response(last.to_json(), status=200)


@article_v.route('/comment/')
def article_comment():
    """
    获取帖子的评论
    :return:
    """
    data = request.args
    # data = aj.load(request.get_data(as_text=True))
    page = int(data['page'])
    limit = int(data['limit'])
    article_id = int(data['article_id'])

    data_all = CommentOrm.orm.find().where(article_id=article_id).order_by('create_time').desc().end()

    comments = data_all.page(limit)

    if len(comments) >= page:
        comments = comments.get(page - 1)
    else:
        return Error('只有这么多了', 400)

    for i, v in enumerate(comments):
        user = UserOrm.orm.find().where(id=v.user_id).first().end()
        comments[i].add_field('user', user.to_dict())

    c_data = comments.to_dict()

    result = {
        'listQuery': {
            'page': page,
            'limit': limit
        },
        'total': len(data_all),
        'data': c_data
    }
    return Response(aj.parse(result), status=200)


@article_v.route('/star/', methods=['POST'])
def article_star():
    data = aj.load(request.get_data(as_text=True))
    has = StarOrm.orm.find().where(article_id=data['article_id'], user_id=data['user_id']).end()
    if has and len(has) > 0:
        return Error('你已经点过赞了', code=400)

    line, last_id = MyFactory.createInstance('article.Star', **data).save()
    last = StarOrm.orm.find().where(id=last_id).first().end()
    return Response(last.to_json(), status=200)


@article_v.route('/types/')
def types():
    """
    查找所有类别
    :return:
    """
    all_cf = ClassificationOrm.orm.find().end()
    return Response(all_cf.to_json(), status=200)


@article_v.route('/speak/', methods=['POST'])
def speak():
    """
    发评论
    :return:
    """
    data = aj.load(request.get_data(as_text=True))
    # user_id = request.form.get('user_id')
    # content = request.form.get('content')
    # article_id = request.form.get('article_id')
    line, last_id = MyFactory.createInstance('article.Comment', **data).save()
    last = CommentOrm.orm.find().where(id=last_id).first().end()
    return Response(last.to_json(), status=200)


@article_v.route('/user_article/')
def my_article():
    """
    指定用户的帖子
    :return:
    """
    data = request.args
    page = int(data['page'])
    limit = int(data['limit'])
    my = ArticleOrm.orm.find().where(user_id=data['user_id']).end()
    count = len(my)
    temp = my.page(limit)
    if len(temp) == 0:
        return Error('没有找到任何帖子', 400)
    if len(temp) >= page:
        my = temp.get(page - 1)
    else:
        return Error('只有这么多了', 400)

    result = {
        'listQuery': {
            'page': page,
            'limit': limit,
        },
        'total': count,
        'data': my.to_dict()
    }

    return Response(aj.parse(result), status=200)


@article_v.route('/user_visual/')
def visual_article():
    """
    用户数据可视化
    :return:
    """

    line = ge_echarts(request.args, ArticleOrm, EchartsLine)
    return Response(aj.parse(line), status=200)


@article_v.route('/star_user_visual/')
def visual_star_article():
    """
    用户最近七天的点赞
    :return:
    """
    line = ge_echarts(request.args, StarOrm, EchartsBar)
    return Response(aj.parse(line), status=200)


@article_v.route('/comment_user_visual/')
def visual_comment_article():
    """
    用户最近七天的评论
    :return:
    """
    line = ge_echarts(request.args, CommentOrm, EchartsBar, title='最近七天发表的评论')
    return Response(aj.parse(line), status=200)
